import { addClassApi, updateClassApi } from "@/api/school/class/index";
import { getTeacherOptionsApi } from "@/api/school/teacher/index";
import { CouresEnum } from "@/enums/school/course.enum";
import { getCourse } from "@/pages/SchoolManage/common/index";
import { Button, Drawer, Form, InputNumber, message, Select } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import type { FormProps } from "antd";
import type { DrawerRefType, DrawerType, OptionsType } from "../types/editDrawerCard.type";
import type { FormPropsType, TableDataType } from "../types/tableCard.type";

const defaultKeys: `${CouresEnum}`[] = ["chinese", "math", "english", "physicalEducation", "music", "computer"];

const EditDrawerCard = forwardRef<DrawerRefType, DrawerType>((props, ref) => {
  const [open, setOpen] = useState(false);
  const [id, setId] = useState<number>();
  const [teacherOptions, setTeacherOptions] = useState<OptionsType[]>();
  const [initialValues, setInitialValues] = useState<Partial<TableDataType>>();
  const [requireFields, setRequireFields] = useState<`${CouresEnum}`[]>(defaultKeys);
  const [messageApi, contextHolder] = message.useMessage();

  const getListData = async () => {
    const { data } = await getTeacherOptionsApi<any, { rows: OptionsType[] }>();
    const rows = data.rows;
    setTeacherOptions(rows);
  };
  const handleTeacherOptions = (type: `${CouresEnum}`) => {
    return teacherOptions?.filter(item => item.type === type);
  };
  const onFinish: FormProps<FormPropsType>["onFinish"] = async values => {
    const { grade, _class, classTeacherId, ...rest } = values;
    const teacher = teacherOptions?.find(item => item.value === classTeacherId);
    const params = {
      ...rest,
      classTeacher: teacher?.label,
      classTeacherId: teacher?.value,
      gradeAndClass: `${grade}-${_class}`,
    } as TableDataType;
    id ? await updateClassApi<TableDataType>(id, params) : await addClassApi<TableDataType>(params);
    messageApi.success("提交成功");
    setTimeout(() => {
      onClose();
    }, 500);
  };
  // * 暴露给父组件的属性, onOpen 是打开抽屉的方法
  useImperativeHandle(ref, () => ({
    onOpen: (record?: TableDataType) => {
      if (record?.id) {
        setId(record.id);
        onSubjectChange(record.subject);
        setInitialValues(() => ({ ...record }));
      } else {
        init();
      }
      setOpen(true);
    },
  }));
  const init = () => {
    setId(undefined);
    setInitialValues({});
    onSubjectChange(0);
  };
  const onClose = () => {
    setOpen(false);
    props.onClose();
  };
  const onSubjectChange = (value: number) => {
    type KeysType = `${CouresEnum}`[];
    const artsKeys: KeysType = ["politics", "history", "geography"]; //文科
    const scienceKeys: KeysType = ["physics", "chemistry", "biology"]; // 理科
    const valueMap: { [index: number]: KeysType } = {
      0: [...artsKeys, ...scienceKeys],
      1: artsKeys,
      2: scienceKeys,
    };
    setRequireFields(() => [...defaultKeys, ...(valueMap[value] || [])]);
  };
  const handleCourse = () => {
    const course = getCourse();
    return course.filter(item => {
      if (requireFields.includes(item.value as `${CouresEnum}`)) return item;
      return false;
    });
  };
  useEffect(() => {
    getListData();
  }, []);
  return (
    <>
      {contextHolder}
      <Drawer
        title={`${id ? "编辑" : "新增"}班级`}
        size="large"
        maskClosable={false}
        destroyOnClose={true}
        onClose={onClose}
        open={open}
      >
        <Form
          name="teacherForm"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          initialValues={initialValues}
          onFinish={onFinish}
        >
          <Form.Item label="年级" name="grade" rules={[{ required: true, message: "请选择年级" }]}>
            <Select
              options={[
                { label: "高一", value: 1 },
                { label: "高二", value: 2 },
                { label: "高三", value: 3 },
              ]}
            />
          </Form.Item>
          <Form.Item label="班级" name="_class" rules={[{ required: true, message: "请选择班级" }]}>
            <InputNumber className="w-full" addonAfter="班" min={1} />
          </Form.Item>
          <Form.Item label="文理科" name="subject" rules={[{ required: true, message: "请选择subject" }]}>
            <Select
              options={[
                { label: "未分科", value: 0 },
                { label: "文科", value: 1 },
                { label: "理科", value: 2 },
              ]}
              onChange={onSubjectChange}
            />
          </Form.Item>
          <Form.Item label="班主任" name="classTeacherId" rules={[{ required: true, message: "请选择班主任" }]}>
            <Select options={teacherOptions} />
          </Form.Item>
          {handleCourse().map(item => {
            return (
              <Form.Item
                label={item.label + "老师"}
                name={item.value + "TeacherId"}
                key={item.value}
                rules={[{ required: true, message: `请选择${item.label}老师` }]}
              >
                <Select options={handleTeacherOptions(item.value as `${CouresEnum}`)} />
              </Form.Item>
            );
          })}
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
});

export default EditDrawerCard;
